﻿using System;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using P2P_Backup.tools;

namespace P2P_Backup.forms.controls
{
    public class PeerListBox : CheckedListBox
    {
        public void SetDataSource(List<RemotePeer> dataSource)
        {
            foreach (RemotePeer p in dataSource)
            {
                Items.Add(p);

            }
            this.ItemCheck += new ItemCheckEventHandler(PeerListBox_ItemCheck);
            dataSource.ItemAdded += new EventHandler<ItemArgs<RemotePeer>>(dataSource_ItemAdded);
            dataSource.ItemRemoved += new EventHandler<ItemArgs<RemotePeer>>(dataSource_ItemRemoved);
            dataSource.Cleared += new EventHandler(dataSource_Cleared);
            
        }

        private void PeerListBox_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            (this.Items[e.Index] as RemotePeer).PerformBackup = (e.NewValue == CheckState.Checked);
        }

        private void dataSource_ItemAdded(object sender, ItemArgs<RemotePeer> e)
        {
            if (this.InvokeRequired) this.BeginInvoke((MethodInvoker)delegate { dataSource_ItemAdded(sender, e); });
            else
            {
                this.Items.Add(e.Item);                
            }
        }

        private void dataSource_ItemRemoved(object sender, ItemArgs<RemotePeer> e)
        {
            if (this.InvokeRequired) this.BeginInvoke((MethodInvoker)delegate { dataSource_ItemRemoved(sender, e); });
            else
            {
                this.Items.Remove(e.Item);
            }
        }

        private void dataSource_Cleared(object sender, EventArgs e)
        {
            this.Items.Clear();
        }
        
    }
}
